﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WoWConnecter
{
    public class Utility
    {
        /// <summary>
        /// Reverses the contents of an array.
        /// </summary>
        /// <typeparam name="T">type of the array</typeparam>
        /// <param name="buffer">array of objects to reverse</param>
        public static void Reverse<T>(T[] buffer)
        {
            Reverse(buffer, buffer.Length);
        }

        /// <summary>
        /// Reverses the contents of an array.
        /// </summary>
        /// <typeparam name="T">type of the array</typeparam>
        /// <param name="buffer">array of objects to reverse</param>
        /// <param name="length">number of objects in the array</param>
        public static void Reverse<T>(T[] buffer, int length)
        {
            for (int i = 0; i < length / 2; i++)
            {
                T temp = buffer[i];
                buffer[i] = buffer[length - i - 1];
                buffer[length - i - 1] = temp;
            }
        }

        /// <summary>
        /// Creates and returns an array of all indices that are set within the given flag field.
        /// eg. 11000011 would result into an array containing: 0,1,6,7
        /// </summary>
        public static uint[] GetSetIndices(uint flags)
        {
            var indices = new List<uint>();
            GetSetIndices(indices, flags);
            return indices.ToArray();
        }

        public static T[] GetSetIndicesEnum<T>(T flags)
        {
            var indices = new List<uint>();
            var uintFlags = (uint)Convert.ChangeType(flags, typeof(uint));
            GetSetIndices(indices, uintFlags);
            if (indices.Count == 0)
            {
                object box = (uint)0;
                return new[] { (T)box };
            }

            var arr = new T[indices.Count];
            for (var i = 0; i < indices.Count; i++)
            {
                var index = indices[i];
                object box = (uint)(1 << (int)(index));
                arr[i] = (T)box;
            }
            return arr;
        }

        public static void GetSetIndices(List<uint> indices, uint flags)
        {
            for (uint i = 0; i < 32; i++)
            {
                if ((flags & 1 << (int)i) != 0)
                {
                    indices.Add(i);
                }
            }
        }
    }
}
